import 'package:flutter/material.dart';
import 'package:flutter_getx/app/base/base_scaffold.dart';
import 'package:flutter_getx/app/base/load_image.dart';
import 'package:flutter_getx/app/base/my_card.dart';
import 'package:flutter_getx/app/base/my_refresh_slivergrid.dart';
import 'package:flutter_getx/app/base/state_layout.dart';
import 'package:flutter_getx/app/config/constant.dart';
import 'package:flutter_getx/core/ext_core.dart';
import 'package:flutter_getx/core/getx/control/cart_control.dart';
import 'package:flutter_getx/core/utils/image_utils.dart';
import 'package:flutter_getx/core/utils/log_utils.dart';
import 'package:flutter_getx/core/utils/show_utils.dart';
import 'package:flutter_getx/ext/ext.dart';
import 'package:flutter_getx/res/colors/colors.dart';
import 'package:flutter_getx/res/colors/colors_dark.dart';
import 'package:flutter_getx/res/colors/theme_colors.dart';
import 'package:flutter_getx/res/dimens/dimens.dart';
import 'package:flutter_getx/res/gaps.dart';
import 'package:flutter_getx/res/strings/strings.dart';
import 'package:flutter_getx/ui/main/main_routers.dart';
import 'package:flutter_getx/ui/main/model/drawer_item.dart';
import 'package:flutter_getx/ui/main/widgets/home_goods_item_widget.dart';
import 'package:flutter_getx/utils/cache_utils.dart';
import 'package:flutter_getx/widgets/auto_scroll_list.dart';
import 'package:flutter_getx/widgets/float_btn_back_top.dart';
import 'package:flutter_getx/widgets/home_app_bar.dart';
import 'package:flutter_getx/widgets/my_widgets.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:get/get.dart';

import 'home_logic.dart';

class HomePage extends StatelessWidget {
  final logic = Get.put(HomeLogic());
  final state = Get.find<HomeLogic>().state;

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetBuilder<HomeLogic>(
      assignId: true,
      builder: (logic) {
        return BaseScaffold(
          keyScaffold: _scaffoldKey,
          isTwiceBack: true,
          backgroundColor: backgroundColor,
          floatingActionButton: FloatingButtonBackTop(state.scrollController),
          floatingActionButtonAnimator: NoScalingAnimation(),
          floatingActionButtonLocation: kBackTopLocation,
          body: DeerSliverGrid(
            slivers: [
              HomeAppBar(
                state.scrollController,
                searchTip: 'searchTip'.tr,
                menuFunc: () => _scaffoldKey.currentState?.openDrawer(),
                searchFunc: () {
                  //toast('click search');
                  Get.toNamed(twoPage);
                },
                cartFunc: () {
                  toast('click cart');
                  CartControl.to.cartNum.value = 2;
                },
              ),
              if (state.data != null)
                SliverToBoxAdapter(
                  child: _topWidget(),
                ),
            ],
            constraints: BoxConstraints(minHeight: Dp.dp_500),
            controller: state.scrollController,
            itemCount: state.data?.recommendGoods?.length ?? 0,
            stateType: state.stateType.value,
            onTapStateLayout: () {
              state.stateType.value = StateType.loading;
              logic.onRefresh();
            },
            onRefresh: logic.onRefresh,
            loadMore: logic.loadMore,
            hasMore: false,
            itemBuilder: _itemBuilder,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              mainAxisSpacing: Dp.dp_8,
              crossAxisSpacing: Dp.dp_8,
              childAspectRatio: goodsRatio,
            ),
            padding: EdgeInsets.symmetric(horizontal: Dp.dp_10),
          ),
          drawer: Drawer(
            child: Container(
              color: backgroundColor,
              child: ListView(
                padding: EdgeInsets.zero,
                children: [
                  GestureDetector(
                    onTap: () {
                      logic.clickLogin();
                    },
                    child: Container(
                      padding: EdgeInsets.only(top: Dp.dp_33, left: Dp.dp_10),
                      height: Dp.dp_75,
                      width: double.infinity,
                      decoration: BoxDecoration(
                          image: DecorationImage(
                        image: AssetImage('bg_drawer_top'.png),
                        colorFilter: ColorFilter.mode(imgColor, imgBlendMode),
                        fit: BoxFit.cover,
                      )),
                      child: Row(
                        children: [
                          LoadImage(
                            'ic_drawer_user'.png,
                            width: Dp.dp_17,
                            height: Dp.dp_18,
                            fit: BoxFit.fill,
                          ),
                          SizedBox(
                            width: Dp.dp_12,
                          ),
                          Text(
                            'Login & Sign up',
                            style: TextStyle(
                              color: Colors.black,
                              fontSize: Sp.sp20,
                              fontWeight: FontWeight.w600,
                              fontStyle: FontStyle.italic,
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                  ..._buildItem([
                    DrawerItem('Switch theme', () {
                      logic.switchTheme();
                    }),
                    DrawerItem('Switch language', () {
                      logic.switchLanguage();
                    }),
                  ]),
                  Gaps.line,
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  List<Widget> _buildItem(List<DrawerItem> items) {
    return List<Widget>.generate(
        items.length,
        (index) => InkWell(
              onTap: items[index].func,
              child: Container(
                height: Dp.dp_55,
                padding: EdgeInsets.only(left: Dp.dp_35),
                alignment: Alignment.centerLeft,
                child: Text(
                  items[index].title,
                  style: subtitle1.copyWith(
                    fontSize: Sp.sp15,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ));
  }

  Widget _topWidget() {
    return Column(
      children: [
        if (state.data?.banner.nullSafe.isNotEmpty ?? false)
          SizedBox(
            height: Dp.dp_170,
            child: Swiper(
              key: UniqueKey(),
              itemBuilder: (BuildContext context, int index) {
                return AspectRatio(
                  aspectRatio: 375 / 170,
                  child: LoadImage(
                    '${state.data?.banner![index].image}',
                    fit: BoxFit.cover,
                    color: imgColor,
                    colorBlendMode: imgBlendMode,
                  ),
                );
              },
              pagination: SwiperPagination(
                  builder: DotSwiperPaginationBuilder(
                      activeColor: Colors.white,
                      color: Colors.white.withOpacity(0.6),
                      size: Dp.dp_5,
                      activeSize: Dp.dp_6)),
              itemCount: state.data!.banner!.length,
              autoplay: true,
              autoplayDelay: 5000,
              onTap: (index) {
                var path = state.data!.banner![index].route.nullSafe;
                if (path.isNotEmpty) {
                  Get.toNamed(path);
                }
              },
            ),
          ),
        if (state.data?.category.nullSafe.isNotEmpty ?? false)
          Container(
            alignment: Alignment.centerLeft,
            height: Dp.dp_111,
            width: double.infinity,
            child: ListView(
              shrinkWrap: true,
              physics: const BouncingScrollPhysics(),
              scrollDirection: Axis.horizontal,
              children: _buildCategoryItems(),
            ),
          ),
        Container(
          width: double.infinity,
          height: Dp.dp_10,
          color: dividerColor,
        ),
        if (state.data?.welfareGoods.nullSafe.isNotEmpty ?? false)
          Container(
            width: double.infinity,
            height: Dp.dp_260,
            padding:
                EdgeInsets.symmetric(vertical: Dp.dp_8, horizontal: Dp.dp_10),
            decoration: BoxDecoration(
                image: DecorationImage(
              image: AssetImage('img_home_bg_welfare'.pathHome),
              colorFilter: ColorFilter.mode(imgColor, imgBlendMode),
              fit: BoxFit.fill,
            )),
            child: Column(
              children: [
                Row(
                  children: [
                    Container(
                      child: LoadImage(
                        'ic_timer'.pathHome,
                        width: Dp.dp_17,
                        height: Dp.dp_17,
                        fit: BoxFit.fill,
                        color: imgColor,
                        colorBlendMode: imgBlendMode,
                      ),
                      decoration: BoxDecoration(
                        boxShadow: <BoxShadow>[
                          BoxShadow(
                              color: Get.isDarkMode ? gradientEndDark : color_3AAEA1,
                              offset: const Offset(0.0, 1.0),
                              blurRadius: 5,
                              spreadRadius: 0.0),
                        ],
                      ),
                    ),
                    SizedBox(
                      width: Dp.dp_5,
                    ),
                    Text(
                      'Welfare commodities',
                      style: subtitle2.copyWith(
                          fontSize: Sp.sp16,
                          fontWeight: FontWeight.w600,
                          shadows: const <BoxShadow>[
                            BoxShadow(
                                color: color_3AAEA1,
                                offset: Offset(0.0, 2.0),
                                blurRadius: 5,
                                spreadRadius: 2.0),
                          ]),
                    ),
                    const Spacer(),
                    Material(
                      color: Colors.black.withOpacity(0.12),
                      borderRadius: BorderRadius.circular(Dp.dp_24),
                      clipBehavior: Clip.antiAlias,
                      child: InkWell(
                        onTap: () {
                          //Get.toNamed(welfarePage);
                        },
                        child: Container(
                          width: Dp.dp_64,
                          height: Dp.dp_24,
                          alignment: Alignment.center,
                          child: Text(
                            "More",
                            style: bodyText2.copyWith(
                                fontSize: Sp.sp12,
                                fontWeight: FontWeight.w600),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  height: Dp.dp_8,
                ),
                Expanded(
                  child: MyCard(
                      child: Container(
                    margin: EdgeInsets.all(Dp.dp_5),
                    child: AutoScrollList(
                      controller: state.scrollControlWelfare,
                      itemCount: intMax - 1,
                      offset: _welfareWH,
                      seconds: 2,
                      child: ListView.builder(
                        itemBuilder: (BuildContext context, int index) {
                          return _buildWelfareItems(index);
                        },
                        itemCount: intMax - 1,
                        controller: state.scrollControlWelfare,
                        shrinkWrap: true,
                        physics: const BouncingScrollPhysics(),
                        scrollDirection: Axis.horizontal,
                      ),
                    ),
                  )),
                ),
              ],
            ),
          ),
        SizedBox(
          height: Dp.dp_20,
        ),
        tipTitle('Recommended today', padding: EdgeInsets.only(left: Dp.dp_10)),
        SizedBox(
          height: Dp.dp_6,
        ),
      ],
    );
  }

  Widget _itemBuilder(BuildContext context, int index) {
    var item = state.data?.recommendGoods?[index];
    return item == null
        ? Gaps.empty
        : HomeGoodsItemWidget(
            item,
            index,
            onTap: () {
              toast('$index');
            },
          );
  }

  List<Widget> _buildCategoryItems() {
    return List<Widget>.generate(state.data!.category!.length, (index) {
      var bean = state.data!.category![index];
      return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          toast('${bean.title}');
        },
        child: Container(
          alignment: Alignment.center,
          padding: EdgeInsets.symmetric(horizontal: Dp.dp_10),
          width: Dp.dp_70,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ClipOval(
                child: LoadImage(
                  '${bean.pic}',
                  width: Dp.dp_48,
                  height: Dp.dp_48,
                  fit: BoxFit.cover,
                  color: imgColor,
                  colorBlendMode: imgBlendMode,
                ),
              ),
              SizedBox(
                height: Dp.dp_10,
              ),
              Text(
                '${bean.title}',
                style: subtitle2.copyWith(fontSize: Sp.sp12),
                textAlign: TextAlign.center,
                maxLines: 2,
              )
            ],
          ),
        ),
      );
    });
  }

  final double _welfareWH = Dp.dp_124;

  Widget _buildWelfareItems(int index) {
    var bean =
        state.data!.welfareGoods![index % state.data!.welfareGoods!.length];
    return InkWell(
      onTap: () {
        toast('${bean.name}');
      },
      child: Container(
        width: _welfareWH,
        padding: EdgeInsets.symmetric(horizontal: Dp.dp_5, vertical: Dp.dp_5),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            LoadImage(
              '${bean.img}',
              width: _welfareWH,
              height: _welfareWH,
              fit: BoxFit.cover,
              color: imgColor,
              colorBlendMode: imgBlendMode,
            ),
            //SizedBox(height: Dp.dp_7,),
            Text(
              '${bean.name}',
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
            ),
            //SizedBox(height: Dp.dp_10,),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                RichText(
                  maxLines: 1,
                  text: TextSpan(
                    text: unit,
                    style: TextStyle(
                      color: color_FF202C,
                      fontSize: Sp.sp12,
                      fontWeight: FontWeight.w600,
                    ),
                    children: [
                      TextSpan(
                        text: bean.price.fmtPrice(),
                        style: TextStyle(
                          fontSize: Sp.sp19,
                        ),
                      ),
                    ],
                  ),
                ),
                RichText(
                  maxLines: 1,
                  text: TextSpan(
                    text: '$unit${bean.originalPrice.fmtPrice()}',
                    style: TextStyle(
                      color: color_999,
                      fontSize: Sp.sp13,
                      decoration: TextDecoration.lineThrough,
                    ),
                    children: [
                      WidgetSpan(
                          child: SizedBox(
                            width: Dp.dp_4,
                          ),
                          style:
                              const TextStyle(decoration: TextDecoration.none)),
                      WidgetSpan(
                          child: LoadImage(
                            'img_home_icon_hot'.pathHome,
                            width: Dp.dp_14,
                            height: Dp.dp_14,
                            fit: BoxFit.fill,
                          ),
                          style:
                              const TextStyle(decoration: TextDecoration.none)),
                    ],
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
